// pages/home/index/index.js
var user = require('../../../services/user.js');
const api = require('../../../api/api.js');
var app = getApp();
var sliderWidth = 96;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    tabs: ["风格", "空间", "类型"],
    categoriesOne: [],
    categoriesTwo: [],
    categoriesThree: [],
    newsGoods: [],
    likeGoods: [],
    temaiGoods: [],
    articles: [],
    minPrice: [],
    isLogin: wx.getStorageSync("isLogin"),
    isNeedRequest: app.globalData.isNeedRequest,
    page: 1,
    pageSize: 12,
    hasMoreData: true,
    userInfo: wx.getStorageSync("userInfo"),
    currentTab: 0,
    // sliderOffset: 0,
    // sliderLeft: 0,
    categoryMore: {
      "id": 0,
      "name": "更多",
      "desc": "",
      "thumbs": "https://zs.bocang.cc/wxxcx/cate_more.png",
    }
  },

  onShareAppMessage: function () {
    return {
      title: '众烁云仓',
      desc: '众烁云仓',
      path: '/pages/home/index/index'
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      isLogin: wx.getStorageSync("isLogin"),
    });
    // that.getUserInfo();
    that.getRequestData();
    that.getLikeGoodsList();

    // that.setData({
    //   sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
    //   sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
    // });
    
  },

  // getUserInfo: function() {
  //   var that = this;
  //   wx.login({
  //     success: function (res) {
  //       var code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
  //       wx.getUserInfo({
  //         success: function (res) {
  //           var iv = res.iv;
  //           var encryptedData = res.encryptedData;
  //           // 下面开始调用注册接口
            

  //           console.log("encryptedData", encryptedData);
  //         }
  //       })
  //     }
  //   })
  // },

  getRequestData: function() {
    let that = this;
    that.getHomeBannerUrl();
    that.getHomeCategory();
    that.getHomeArticle();
    that.getHomeNewProduct();
    that.getTeMaiGoods();
  },

  getHomeBannerUrl: function() {
    let that = this;
    wx.request({
      url: api.HomeBannerUrl,
      success: function (res) {
        that.setData({
          banners: res.data.banners
        })
      },
      fail: function (res) { },
      complete: function (res) { },
    });
  },

  getHomeCategory: function() {
    let that = this;
    wx.request({
      url: api.HomeCategory,
      data: {
        page: 1,
        per_page: 20,
        category: null,
        shop: null,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.error_code === 0) {
          app.globalData.isNeedRequest = false;
          let categories = res.data.categories;
          for (var i = 0; i < categories.length; i++) {
            if (i == 0) {
              let categories1 = categories[i].categories;
              let categories2 = [];
              for (var j = 0; j < categories1.length; j++) {
                if (j <= 6) {
                  categories2.push(categories1[j])
                }
              }
              if (categories1.length >= 7) {
                categories2.push(that.data.categoryMore)
              }
              that.setData({
                categoriesOne: categories2
              });
            }
            if (i == 1) {
              let categories1 = categories[i].categories;
              let categories2 = [];
              for (var j = 0; j < categories1.length; j++) {
                if (j <= 6) {
                  categories2.push(categories1[j])
                }
              }
              if (categories1.length >= 7) {
                categories2.push(that.data.categoryMore)
              }
              that.setData({
                categoriesTwo: categories2
              });
            }
            if (i == 2) {
              let categories1 = categories[i].categories;
              let categories2 = [];
              for (var j = 0; j < categories1.length; j++) {
                if (j <= 6) {
                  categories2.push(categories1[j])
                }
              }
              if (categories1.length >= 7) {
                categories2.push(that.data.categoryMore)
              }
              that.setData({
                categoriesThree: categories2
              });
            }
          }
        }
      },
    });
  },

  getHomeArticle: function() {
    let that = this;
    wx.request({
      url: api.HomeArticle,
      data: {
        id: 14,
        page: 1,
        per_page: 20,
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        if (res.data.error_code === 0) {
          that.setData({
            articles: res.data.articles
          })
        }
      }
    });
  },

  getHomeNewProduct: function() {
    let that = this;
    wx.request({
      url: api.HomeNewProduct,
      data: {
        page: 1,
        per_page: 36,
        type: 1,
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res);
        if (res.data.error_code === 0) {
          that.setData({
            newsGoods: res.data.products,
          });
          // that.getMinPrice(res.data.products);
        }
      }
    });
  },

  // getAttrs: function(products) {
  //   let that = this;
  //   var products = products;
  //   var temp = "";
  //   var minPrice = [];
  //   for (var i = 0; i < products.length; i++) {
  //     var properties = products[i].properties;
  //     for (var j = 0; j < properties.length; j++) {
  //       var id = properties[i].id;
  //       if (id == 17) {
  //         var attrs = properties[i];
  //         temp = that.getMinPrice(attrs);
  //       }
  //       minPrice.push(temp)
  //     }
  //   }
  //   that.setData({
  //     minPrice: minPrice
  //   })
  // },

  // getMinPrice: function (attrs) {
  //   let that = this;
  //   var level_id = that.data.userInfo.level_id;
  //   var attrprice = "attr_price_5";
  //   switch (level_id) {
  //     case 104:
  //       attrprice = "attr_price_5";
  //       break;
  //     case 103:
  //       attrprice = "attr_price_4";
  //       break;
  //     case 102:
  //       attrprice = "attr_price_3";
  //       break;
  //     case 101:
  //       attrprice = "attr_price_2";
  //       break;
  //     case 100:
  //       attrprice = "attr_price_1";
  //       break;
  //     case 99:
  //       attrprice = "attr_price_2";
  //       break;
  //   }
  //   var temp = attrs[0].attrprice;
  //   for (var i = 0; i < attrs.length; i++) {
  //     if (attrs[i].attrprice < temp) {
  //       temp = attrs[i].attrprice;
  //     }
  //   }
  //   return temp;
  // },

  getTeMaiGoods: function() {
    let that = this;
    wx.request({
      url: api.HomeTeMaiProduct,
      data: {
        page: 1,
        per_page: 10,
        brand: "",
        category: "214",
        filter_attr: "",
        shop: "",
        keyword: "",
        sort_key: "",
        sort_value: "",
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res);
        if (res.data.error_code === 0) {
          that.setData({
            temaiGoods: res.data.products,
          });
          // that.getMinPrice(res.data.products);
        }
      }
    });
  },

  //精品推荐
  getSpecailGoods: function () {
    let that = this;
    wx.request({
      url: api.HomeTeMaiProduct,
      data: {
        page: 1,
        per_page: 6,
        type: "2"
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res);
        if (res.data.error_code === 0) {
          that.setData({
            temaiGoods: res.data.products,
          });
          // that.getMinPrice(res.data.products);
        }
      }
    });
  },

  getLikeGoodsList: function () {
    var that = this;
    wx.showLoading({
      "mask": false,
      title: '加载中...'
    });
    wx.request({
      url: api.HomeLikeProduct,
      data: {
        page: this.data.page,
        per_page: 20,
        brand: "",
        category: "",
        filter_attr: "",
        shop: "",
        keyword: "",
        sort_key: Math.floor(Math.random() * 6 + 1),
        sort_value: 2,
      },
      method: "POST",
      header: {
        'Content-Type': 'application/json',
        'X-bocang-Authorization': wx.getStorageSync('token')
      },
      success: function (res) {
        var likeGoodsListTmp = that.data.likeGoods;
        if (res.data.error_code == 0) {
          if (that.data.page == 1) {
            likeGoodsListTmp = [];
          }
          if (res.data.products.length < that.data.pageSize) {
            that.setData({
              likeGoods: likeGoodsListTmp.concat(res.data.products),
              hasMoreData: false,
            });
          } else {
            that.setData({
              likeGoods: likeGoodsListTmp.concat(res.data.products),
              hasMoreData: true,
              page: that.data.page + 1,
            });
          }
        }
      }
    });
    setTimeout(function () {
      wx.hideLoading();
    }, 300);
  },

  navbarTap: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      currentTab: e.currentTarget.id
    });
  },

  toSearchTap: function() {
    wx.navigateTo({
      url: '/pages/home/search/search',
    })
  },
  
  CallPhoneTap: function() {
    wx.makePhoneCall({
      phoneNumber: api.PhoneCall
    })
  },

  toMessagesTap: function () {
    wx.navigateTo({
      url: '/pages/message/message/message',
    })
  },

  toProdetailTap: function(e) {
    var id = e.currentTarget.dataset.id;
    if (id == 0) {
      wx.switchTab({
        url: '/pages/classify/index/index',
      })
    } else {
      wx.navigateTo({
        url: '/pages/category/category/category?id=' + id,
      })
    }
  },

  toSeeMoreXPTap: function() {
    wx.navigateTo({
      url: '/pages/category/category/category?id=' + 5,
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    let oldGoods = that.data.newsGoods;
    that.setData({
      isLogin: wx.getStorageSync("isLogin"),
    });
    if (app.globalData.isNeedRequest) {
      that.getRequestData();
      that.getLikeGoodsList();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    var that = this;
    this.setData({
      page: 1
    });
    this.getRequestData();
    this.getLikeGoodsList();
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    // 页面上拉触底事件的处理函数
    if (that.data.hasMoreData) {
      that.getLikeGoodsList();
    } else {
      wx.showToast({
        title: '没有更多数据',
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
})